// 文件路径: F:\demo\vue3\src\widget\table\composables\resizeModule.ts
import type { Ref } from 'vue';
import type { Column } from '../type';

export interface ResizeModuleOptions {
  tableRef: Ref<HTMLElement | null>;
  localColumns: Ref<Column[]>;
  emit: (event: string, ...args: any[]) => void;
}

export function useColumnResize(options: ResizeModuleOptions) {
  const { tableRef, localColumns, emit } = options;

  // 创建拖拽指示器
  const createResizeIndicator = (e: MouseEvent) => {
    let proxy = document.querySelector('.resize-indicator') as HTMLElement;
    if (!proxy) {
      proxy = document.createElement('div');
      proxy.className = 'resize-indicator';
      proxy.style.cssText = `
        position: fixed;
        top: ${e.clientY - 10}px;
        left: ${e.clientX}px;
        width: 3px;
        height: ${tableRef.value?.clientHeight}px;
        background-color: #409eff;
        z-index: 9999;
        pointer-events: none;
        opacity: 0.8;`;
      document.body.appendChild(proxy);
    } else {
      proxy.style.left = e.clientX + 'px';
      proxy.style.display = 'block';
    }
    return proxy;
  };

  // 处理列宽调整开始
  const handleResizeStart = (e: MouseEvent, columnIndex: number) => {
    e.preventDefault();
    e.stopPropagation();

    if (!tableRef.value) return;

    const startX = e.clientX;
    const column = localColumns.value[columnIndex];
    const startWidth = column.width || 100;

    // 获取最小和最大宽度设置
    const minWidth = column.minWidth || 60;
    const maxWidth = column.maxWidth || 400;

    // 创建指示器
    const indicator = createResizeIndicator(e);

    const mouseMoveHandler = (e: MouseEvent) => {
      e.preventDefault();
      e.stopPropagation();

      // 更新指示器位置
      if (indicator) {
        indicator.style.left = e.clientX + 'px';
      }
    };

    const mouseUpHandler = (e: MouseEvent) => {
      e.preventDefault();
      e.stopPropagation();

      // 计算并应用最终列宽
      const deltaX = e.clientX - startX;
      const finalWidth = Math.max(minWidth, Math.min(startWidth + deltaX, maxWidth));

      // 更新列宽
      if (localColumns.value[columnIndex]) {
        localColumns.value[columnIndex].width = finalWidth;
      }

      // 触发事件
      emit('columnResize', columnIndex, finalWidth);

      // 清理
      document.removeEventListener('mousemove', mouseMoveHandler);
      document.removeEventListener('mouseup', mouseUpHandler);

      // 隐藏指示器
      if (indicator) {
        indicator.style.display = 'none';
      }
    };

    document.addEventListener('mousemove', mouseMoveHandler);
    document.addEventListener('mouseup', mouseUpHandler, { once: true });
  };

  return {
    handleResizeStart
  };
}
